// pages/gallery/gallery.js
Page({
  data: {
    photos: [],
    currentFilter: 'all',
    isLoading: false,
    isRefreshing: false,
    hasMore: true,
    page: 1,
    pageSize: 20
  },

  onLoad() {
    this.loadPhotos()
  },

  onShow() {
    const openid = wx.getStorageSync('openid')
    if (!openid) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }
  },

  async loadPhotos(reset = false) {
    if (this.data.isLoading) return

    this.setData({ isLoading: true })
    
    const openid = wx.getStorageSync('openid')
    const { currentFilter, page, pageSize } = this.data

    try {
      const app = getApp();
      const apiUrl = app.globalData.api_url;
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: apiUrl + 'api/user/files',
          method: 'GET',
          data: {
            file_type: currentFilter === 'all' ? null : currentFilter,
            limit: pageSize,
            offset: (page - 1) * pageSize
          },
          header: {
            'openid': openid
          },
          success: resolve,
          fail: reject
        })
      })

      if (response.data && response.data.success) {
        const app = getApp();
        const apiUrl = app.globalData.api_url;
        const safeUrl = (path) => path ? (path.startsWith('/') ? path.substring(1) : path) : '';
        const newPhotos = response.data.files.map(file => ({
          ...file,
          date: this.formatDate(file.created_at),
          fullUrl: apiUrl + safeUrl(file.url)
        }))

        if (reset) {
          this.setData({
            photos: newPhotos,
            page: 1,
            hasMore: newPhotos.length === pageSize
          })
        } else {
          this.setData({
            photos: [...this.data.photos, ...newPhotos],
            hasMore: newPhotos.length === pageSize
          })
        }
      }
    } catch (error) {
      console.error('加载照片失败:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({
        isLoading: false,
        isRefreshing: false
      })
    }
  },

  setFilter(e) {
    const { filter } = e.currentTarget.dataset
    this.setData({
      currentFilter: filter,
      photos: [],
      page: 1,
      hasMore: true
    })
    this.loadPhotos(true)
  },

  onRefresh() {
    this.setData({
      photos: [],
      page: 1,
      hasMore: true,
      isRefreshing: true
    })
    this.loadPhotos(true)
  },

  loadMore() {
    if (!this.data.hasMore || this.data.isLoading) return
    
    this.setData({
      page: this.data.page + 1
    })
    this.loadPhotos()
  },

  previewImage(e) {
    const { url } = e.currentTarget.dataset
    const app = getApp();
    const apiUrl = app.globalData.api_url;
    const safeUrl = (path) => path ? (path.startsWith('/') ? path.substring(1) : path) : '';
    const urls = this.data.photos.map(photo => apiUrl + safeUrl(photo.url))
    
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  downloadImage(e) {
    const { url } = e.currentTarget.dataset
    
    wx.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              })
            },
            fail: () => {
              wx.showToast({
                title: '保存失败，请检查权限',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })
  },

  deletePhoto(e) {
    const { path } = e.currentTarget.dataset
    
    wx.showModal({
      title: '删除照片',
      content: '确定要删除这张照片吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          this.performDelete(path)
        }
      }
    })
  },

  async performDelete(path) {
    const openid = wx.getStorageSync('openid')
    const app = getApp();
    const apiUrl = app.globalData.api_url;
    
    try {
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: apiUrl + 'api/user/files/' + encodeURIComponent(path),
          method: 'DELETE',
          header: {
            'openid': openid
          },
          success: resolve,
          fail: reject
        })
      })

      if (response.data && response.data.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.loadPhotos(true)
      } else {
        wx.showToast({
          title: response.data.message || '删除失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('删除照片失败:', error)
      wx.showToast({
        title: '删除失败，请重试',
        icon: 'none'
      })
    }
  },

  goBack() {
    wx.navigateBack()
  },

  goToEdit() {
    wx.switchTab({
      url: '/pages/edit/edit'
    })
  },

  formatDate(dateString) {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now - date
    
    if (diff < 24 * 60 * 60 * 1000) {
      return '今天'
    } else if (diff < 48 * 60 * 60 * 1000) {
      return '昨天'
    } else {
      return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
    }
  },

  formatDeleteDate(deleteAt) {
    const date = new Date(deleteAt)
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }
})